package controller

import (
	"github.com/valyala/fasthttp"

	log "github.com/Sirupsen/logrus"
	"ccGame/common"
	"ccGame/mongo"
	"gopkg.in/mgo.v2/bson"
)

// 玩家登录处理
//
func LoginAction(ctx *fasthttp.RequestCtx){

	mobile := string(ctx.FormValue("mobile"))
	password := string(ctx.FormValue("password"))

	if mobile == "" || password == "" {
		common.SendMsg(ctx,400,"账号或者密码错误!!")
		return
	}

	var userInfo  = &mongo.User{}
	err := mongo.FindOne("user",bson.M{"mobile":mobile,"password":password},bson.M{},userInfo)
	if err != nil {
		log.Error(err.Error())
		if err.Error() == "not found" {
			common.SendMsg(ctx,501,"账号不存在!! 请注册!")
			return
		}
		common.SendMsg(ctx,501,"数据查询错误!")
		return
	}
	var tokenUserInfo = &common.TokenUserInfo{}

	tokenUserInfo.Username = userInfo.Username
	tokenUserInfo.UserId = userInfo.UserId

	token, err := common.CreateToken(tokenUserInfo)

	if err != nil {
		common.SendMsg(ctx,501,"数据签名失败!")
		return
	}
	ctx.Response.Header.Add("Authorization",token)
	common.SendMsg(ctx,200,userInfo)
}